<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>植物黄叶率智能检测系统</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="icon" href="/nsx_logo.svg">
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.8/dist/chart.umd.min.js"></script>

    <!-- 配置Tailwind自定义颜色和字体 -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#2E7D32',      // 主色调：绿色（代表植物健康）
                        secondary: '#8D6E63',    // 辅助色：棕色（代表土壤/树干）
                        warning: '#FFA000',      // 警告色：黄色（代表黄叶）
                        danger: '#D32F2F',       // 危险色：红色（代表严重问题）
                        neutral: '#F5F5F5',      // 中性色：浅灰
                        'neutral-dark': '#263238' // 深色模式背景
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                    },
                }
            }
        }
    </script>

    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .shadow-soft {
                box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
            }
            .transition-all-300 {
                transition: all 300ms ease-in-out;
            }
            .scrollbar-hide::-webkit-scrollbar {
                display: none;
            }
            .scrollbar-hide {
                -ms-overflow-style: none;
                scrollbar-width: none;
            }
        }
    </style>
</head>

<body class="bg-gray-50 text-gray-800 min-h-screen flex flex-col transition-all duration-300" id="app-body">
<!-- 顶部导航栏 -->
<header class="bg-white shadow-md sticky top-0 z-50 transition-all duration-300" id="main-header">
    <div class="container mx-auto px-4 py-3 flex items-center justify-between">
        <div class="flex items-center space-x-2">
            <i class="fa fa-leaf text-primary text-2xl"></i>
            <h1 class="text-xl font-bold text-primary">植物黄叶率智能检测系统</h1>
        </div>

        <div class="flex items-center space-x-6">
            <button class="text-gray-600 hover:text-primary transition-all-300" id="help-btn">
                <i class="fa fa-question-circle mr-1"></i>帮助
            </button>
            <button class="text-gray-600 hover:text-primary transition-all-300" id="history-btn">
                <i class="fa fa-history mr-1"></i>历史记录
            </button>
            <button class="flex items-center text-gray-600 hover:text-primary transition-all-300" id="theme-toggle">
                <i class="fa fa-moon-o mr-1"></i>
                <span>深色模式</span>
            </button>
        </div>
    </div>
</header>

<!-- 主要内容区 -->
<main class="flex-grow container mx-auto px-4 py-6">
    <div class="grid grid-cols-1 lg:grid-cols-12 gap-6">

        <!-- 左侧功能区 -->
        <div class="lg:col-span-3 bg-white rounded-xl shadow-soft p-5 h-fit">
            <h2 class="text-lg font-semibold mb-4 flex items-center">
                <i class="fa fa-cogs text-primary mr-2"></i>功能操作
            </h2>

            <!-- 上传区域 -->
            <div class="mb-6">
                <label class="block text-sm font-medium text-gray-700 mb-2">上传植物照片</label>
                <div class="border-2 border-dashed border-gray-300 rounded-lg p-6 text-center hover:border-primary transition-all-300 cursor-pointer" id="upload-area">
                    <input type="file" id="file-upload" accept="image/*" class="hidden" multiple>
                    <i class="fa fa-cloud-upload text-3xl text-gray-400 mb-2"></i>
                    <p class="text-sm text-gray-500">点击或拖拽照片到此处上传<br>支持 JPG、PNG 格式</p>
                </div>
                <div class="mt-3 text-xs text-gray-500">
                    <i class="fa fa-info-circle mr-1"></i> 建议上传清晰的叶片特写，光线充足效果更佳
                </div>
            </div>

            <!-- 检测设置 -->
            <div class="mb-6">
                <label class="block text-sm font-medium text-gray-700 mb-2">检测模式</label>
                <div class="space-y-2">
                    <label class="flex items-center p-2 border border-gray-200 rounded-md hover:bg-gray-50 cursor-pointer">
                        <input type="radio" name="detection-mode" value="color" checked class="mr-2 text-primary">
                        <span>颜色分析（快速）</span>
                        <span class="ml-auto text-xs text-gray-500">基于OpenCV</span>
                    </label>
                    <label class="flex items-center p-2 border border-gray-200 rounded-md hover:bg-gray-50 cursor-pointer">
                        <input type="radio" name="detection-mode" value="yolo" class="mr-2 text-primary">
                        <span>深度学习（精确）</span>
                        <span class="ml-auto text-xs text-gray-500">基于YOLO模型</span>
                    </label>
                </div>
            </div>

            <!-- 参数设置 -->
            <div class="mb-6 p-3 bg-gray-50 rounded-lg">
                <h3 class="text-sm font-medium text-gray-700 mb-3">颜色检测参数</h3>

                <div class="space-y-3">
                    <div>
                        <label class="block text-xs text-gray-600 mb-1">绿色阈值（下限）</label>
                        <div class="flex items-center">
                            <input type="text" value="35,40,40" class="text-xs flex-grow p-1.5 border border-gray-300 rounded" id="green-low">
                        </div>
                    </div>

                    <div>
                        <label class="block text-xs text-gray-600 mb-1">绿色阈值（上限）</label>
                        <div class="flex items-center">
                            <input type="text" value="77,255,255" class="text-xs flex-grow p-1.5 border border-gray-300 rounded" id="green-high">
                        </div>
                    </div>

                    <div>
                        <label class="block text-xs text-gray-600 mb-1">黄色阈值（下限）</label>
                        <div class="flex items-center">
                            <input type="text" value="20,40,40" class="text-xs flex-grow p-1.5 border border-gray-300 rounded" id="yellow-low">
                        </div>
                    </div>

                    <div>
                        <label class="block text-xs text-gray-600 mb-1">黄色阈值（上限）</label>
                        <div class="flex items-center">
                            <input type="text" value="35,255,255" class="text-xs flex-grow p-1.5 border border-gray-300 rounded" id="yellow-high">
                        </div>
                    </div>
                </div>
            </div>

            <!-- 操作按钮 -->
            <div class="space-y-3">
                <button id="start-detection" class="w-full bg-primary hover:bg-primary/90 text-white font-medium py-2.5 px-4 rounded-lg transition-all-300 flex items-center justify-center disabled:opacity-50 disabled:cursor-not-allowed" disabled>
                    <i class="fa fa-play mr-2"></i>开始检测
                </button>
                <button id="export-result" class="w-full bg-gray-200 hover:bg-gray-300 text-gray-800 font-medium py-2 px-4 rounded-lg transition-all-300 flex items-center justify-center disabled:opacity-50 disabled:cursor-not-allowed" disabled>
                    <i class="fa fa-download mr-2"></i>导出结果
                </button>
                <button id="clear-all" class="w-full bg-gray-100 hover:bg-gray-200 text-gray-700 font-medium py-2 px-4 rounded-lg transition-all-300 flex items-center justify-center">
                    <i class="fa fa-trash mr-2"></i>清除内容
                </button>
            </div>
        </div>

        <!-- 中间预览区 -->
        <div class="lg:col-span-5 flex flex-col">
            <div class="bg-white rounded-xl shadow-soft p-5 flex-grow">
                <h2 class="text-lg font-semibold mb-4 flex items-center">
                    <i class="fa fa-image text-primary mr-2"></i>图片预览与检测结果
                </h2>

                <!-- 初始状态提示 -->
                <div id="initial-state" class="flex flex-col items-center justify-center h-[400px] text-center">
                    <i class="fa fa-picture-o text-5xl text-gray-300 mb-4"></i>
                    <p class="text-gray-500 max-w-md">上传一张植物的照片，系统将自动检测叶片状态并分析黄叶率</p>
                </div>

                <!-- 加载状态 -->
                <div id="loading-state" class="hidden flex flex-col items-center justify-center h-[400px]">
                    <div class="w-16 h-16 border-4 border-primary border-t-transparent rounded-full animate-spin mb-4"></div>
                    <p class="text-gray-600">正在分析叶片状态，请稍候...</p>
                    <div class="mt-4 w-full bg-gray-200 rounded-full h-2.5">
                        <div class="bg-primary h-2.5 rounded-full" id="progress-bar" style="width: 0%"></div>
                    </div>
                    <p class="text-xs text-gray-500 mt-2" id="progress-text">0% 完成</p>
                </div>

                <!-- 图片预览与检测标记 -->
                <div id="preview-container" class="hidden relative bg-gray-100 rounded-lg overflow-hidden">
                    <div class="absolute top-3 right-3 z-10 flex space-x-2">
                        <button class="bg-white/80 hover:bg-white text-gray-700 p-2 rounded-full shadow-md transition-all-300" title="放大" id="zoom-in">
                            <i class="fa fa-search-plus"></i>
                        </button>
                        <button class="bg-white/80 hover:bg-white text-gray-700 p-2 rounded-full shadow-md transition-all-300" title="缩小" id="zoom-out">
                            <i class="fa fa-search-minus"></i>
                        </button>
                        <button class="bg-white/80 hover:bg-white text-gray-700 p-2 rounded-full shadow-md transition-all-300" title="重置" id="zoom-reset">
                            <i class="fa fa-refresh"></i>
                        </button>
                    </div>

                    <!-- 图像查看器 -->
                    <div class="relative overflow-auto" id="image-viewer" style="height: 400px;">
                        <img id="preview-image" src="" alt="植物照片" class="w-full h-auto transition-transform duration-300" style="transform: scale(1);">

                        <!-- 检测结果图层 -->
                        <div id="detection-overlays" class="absolute top-0 left-0 pointer-events-none"></div>

                        <!-- 颜色掩码图层 -->
                        <div id="mask-overlay" class="absolute top-0 left-0 opacity-0 transition-opacity duration-300 pointer-events-none"></div>
                    </div>

                    <!-- 检测结果切换 -->
                    <div class="absolute bottom-3 left-3 z-10 flex space-x-2">
                        <button class="bg-white/80 hover:bg-white text-gray-700 px-3 py-1 rounded-md shadow-md transition-all-300 text-sm active" id="view-original">
                            原图
                        </button>
                        <button class="bg-white/80 hover:bg-white text-gray-700 px-3 py-1 rounded-md shadow-md transition-all-300 text-sm" id="view-mask">
                            颜色掩码
                        </button>
                        <button class="bg-white/80 hover:bg-white text-gray-700 px-3 py-1 rounded-md shadow-md transition-all-300 text-sm" id="view-combined">
                            叠加视图
                        </button>
                    </div>
                </div>
            </div>

            <!-- 图片导航 -->
            <div class="mt-6 bg-white rounded-xl shadow-soft p-4">
                <h3 class="text-sm font-medium text-gray-700 mb-3">已上传图片</h3>
                <div class="flex space-x-3 overflow-x-auto scrollbar-hide pb-2" id="image-thumbs">
                    <!-- 缩略图将通过JS动态添加 -->
                    <div class="text-gray-400 text-sm flex items-center justify-center w-20 h-20 border-2 border-dashed rounded-lg">
                        <i class="fa fa-plus"></i>
                    </div>
                </div>
            </div>
        </div>

        <!-- 右侧数据面板 -->
        <div class="lg:col-span-4 space-y-6">
            <!-- 黄叶率概览 -->
            <div class="bg-white rounded-xl shadow-soft p-5">
                <h2 class="text-lg font-semibold mb-4 flex items-center">
                    <i class="fa fa-bar-chart text-primary mr-2"></i>黄叶率分析
                </h2>

                <div id="no-data-state" class="flex flex-col items-center justify-center py-10 text-center">
                    <i class="fa fa-pie-chart text-4xl text-gray-300 mb-3"></i>
                    <p class="text-gray-500">上传照片并完成检测后显示分析结果</p>
                </div>

                <div id="result-stats" class="hidden">
                    <div class="flex flex-col items-center mb-6">
                        <div class="relative w-40 h-40 mb-3">
                            <canvas id="yellow-leaf-chart"></canvas>
                            <div class="absolute inset-0 flex items-center justify-center flex-col">
                                <span id="yellow-rate" class="text-3xl font-bold text-warning">0%</span>
                                <span class="text-xs text-gray-500">黄叶率</span>
                            </div>
                        </div>

                        <div class="grid grid-cols-3 gap-2 w-full text-center">
                            <div class="bg-gray-50 p-3 rounded-lg">
                                <p class="text-xs text-gray-500">总叶片像素</p>
                                <p class="text-lg font-semibold" id="total-pixels">0</p>
                            </div>
                            <div class="bg-green-50 p-3 rounded-lg">
                                <p class="text-xs text-gray-500">健康叶像素</p>
                                <p class="text-lg font-semibold text-primary" id="healthy-pixels">0</p>
                            </div>
                            <div class="bg-yellow-50 p-3 rounded-lg">
                                <p class="text-xs text-gray-500">黄叶像素</p>
                                <p class="text-lg font-semibold text-warning" id="yellow-pixels">0</p>
                            </div>
                        </div>

                        <div class="mt-4 text-sm text-gray-600">
                            <p><i class="fa fa-info-circle text-primary mr-1"></i> 检测方法: <span id="detection-method">颜色分析</span></p>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 生长状态评估 -->
            <div class="bg-white rounded-xl shadow-soft p-5">
                <h2 class="text-lg font-semibold mb-4 flex items-center">
                    <i class="fa fa-line-chart text-primary mr-2"></i>生长状态评估
                </h2>

                <div id="growth-state" class="hidden">
                    <div class="flex items-center mb-4">
                        <div class="w-12 h-12 rounded-full flex items-center justify-center mr-3" id="status-indicator">
                            <i class="fa fa-check text-white text-xl"></i>
                        </div>
                        <div>
                            <h3 class="font-semibold text-lg" id="status-text">生长状态良好</h3>
                            <p class="text-sm text-gray-500" id="status-desc">叶片健康，黄叶比例正常</p>
                        </div>
                    </div>

                    <div class="space-y-3">
                        <div>
                            <div class="flex justify-between text-sm mb-1">
                                <span>整体健康度</span>
                                <span id="health-score">90</span>/100
                            </div>
                            <div class="w-full bg-gray-200 rounded-full h-2">
                                <div id="health-meter" class="bg-primary h-2 rounded-full" style="width: 90%"></div>
                            </div>
                        </div>

                        <div>
                            <div class="flex justify-between text-sm mb-1">
                                <span>叶片颜色均匀度</span>
                                <span id="uniformity-score">85</span>/100
                            </div>
                            <div class="w-full bg-gray-200 rounded-full h-2">
                                <div id="uniformity-meter" class="bg-green-500 h-2 rounded-full" style="width: 85%"></div>
                            </div>
                        </div>
                    </div>
                </div>

                <div id="no-growth-data" class="flex flex-col items-center justify-center py-6 text-center">
                    <i class="fa fa-leaf text-4xl text-gray-300 mb-3"></i>
                    <p class="text-gray-500">完成检测后显示生长状态评估</p>
                </div>
            </div>

            <!-- 养护建议 -->
            <div class="bg-white rounded-xl shadow-soft p-5">
                <h2 class="text-lg font-semibold mb-4 flex items-center">
                    <i class="fa fa-lightbulb-o text-primary mr-2"></i>养护建议
                </h2>

                <div id="care-advice" class="hidden space-y-3">
                    <div id="advice-content" class="text-gray-700 text-sm space-y-2">
                        <!-- 建议内容将通过JS动态添加 -->
                    </div>
                </div>

                <div id="no-advice" class="flex flex-col items-center justify-center py-6 text-center">
                    <i class="fa fa-book text-4xl text-gray-300 mb-3"></i>
                    <p class="text-gray-500">根据检测结果提供个性化养护建议</p>
                </div>
            </div>
        </div>
    </div>
</main>

<!-- 页脚 -->
<footer class="bg-white border-t mt-8 py-4" id="main-footer">
    <div class="container mx-auto px-4 text-center text-sm text-gray-500">
        <p>© 2025 植物黄叶率智能检测系统 | 基于OpenCV和YOLO技术</p>
    </div>
</footer>

<!-- 帮助模态框 -->
<div id="help-modal" class="fixed inset-0 bg-black/50 z-50 flex items-center justify-center hidden">
    <div class="bg-white rounded-xl max-w-md w-full max-h-[80vh] overflow-y-auto m-4">
        <div class="p-5 border-b flex justify-between items-center">
            <h3 class="text-lg font-semibold">使用帮助</h3>
            <button id="close-help" class="text-gray-500 hover:text-gray-700">
                <i class="fa fa-times"></i>
            </button>
        </div>
        <div class="p-5 space-y-4">
            <div>
                <h4 class="font-medium mb-2">如何上传照片？</h4>
                <p class="text-sm text-gray-600">点击左侧上传区域或直接拖拽图片到上传区域，支持一次上传多张图片。</p>
            </div>
            <div>
                <h4 class="font-medium mb-2">两种检测模式有何区别？</h4>
                <p class="text-sm text-gray-600">
                    1. 颜色分析（快速）：基于OpenCV的颜色阈值分析，速度快但精度较低<br>
                    2. 深度学习（精确）：基于YOLO模型的叶片检测，精度高但需要更长处理时间
                </p>
            </div>
            <div>
                <h4 class="font-medium mb-2">如何获得更准确的结果？</h4>
                <p class="text-sm text-gray-600">
                    1. 确保照片光线充足，避免逆光拍摄<br>
                    2. 尽量拍摄清晰的叶片特写<br>
                    3. 确保叶片无遮挡<br>
                    4. 可调整颜色阈值参数优化检测结果
                </p>
            </div>
            <div>
                <h4 class="font-medium mb-2">如何解释黄叶率？</h4>
                <p class="text-sm text-gray-600">
                    黄叶率是黄色叶片像素占总叶片像素的百分比，<br>
                    - 0-10%：正常范围<br>
                    - 10-30%：需要关注<br>
                    - 30%以上：存在明显问题
                </p>
            </div>
        </div>
    </div>
</div>

<script>
    // DOM元素引用
    const appBody = document.getElementById('app-body');
    const mainHeader = document.getElementById('main-header');
    const mainFooter = document.getElementById('main-footer');
    const themeToggle = document.getElementById('theme-toggle');
    const uploadArea = document.getElementById('upload-area');
    const fileUpload = document.getElementById('file-upload');
    const startDetection = document.getElementById('start-detection');
    const exportResult = document.getElementById('export-result');
    const clearAll = document.getElementById('clear-all');
    const initialState = document.getElementById('initial-state');
    const loadingState = document.getElementById('loading-state');
    const previewContainer = document.getElementById('preview-container');
    const previewImage = document.getElementById('preview-image');
    const detectionOverlays = document.getElementById('detection-overlays');
    const maskOverlay = document.getElementById('mask-overlay');
    const progressBar = document.getElementById('progress-bar');
    const progressText = document.getElementById('progress-text');
    const noDataState = document.getElementById('no-data-state');
    const resultStats = document.getElementById('result-stats');
    const yellowLeafChart = document.getElementById('yellow-leaf-chart');
    const yellowRate = document.getElementById('yellow-rate');
    const totalPixels = document.getElementById('total-pixels');
    const healthyPixels = document.getElementById('healthy-pixels');
    const yellowPixels = document.getElementById('yellow-pixels');
    const detectionMethod = document.getElementById('detection-method');
    const noGrowthData = document.getElementById('no-growth-data');
    const growthState = document.getElementById('growth-state');
    const statusIndicator = document.getElementById('status-indicator');
    const statusText = document.getElementById('status-text');
    const statusDesc = document.getElementById('status-desc');
    const healthScore = document.getElementById('health-score');
    const healthMeter = document.getElementById('health-meter');
    const uniformityScore = document.getElementById('uniformity-score');
    const uniformityMeter = document.getElementById('uniformity-meter');
    const noAdvice = document.getElementById('no-advice');
    const careAdvice = document.getElementById('care-advice');
    const adviceContent = document.getElementById('advice-content');
    const imageThumbs = document.getElementById('image-thumbs');
    const helpBtn = document.getElementById('help-btn');
    const helpModal = document.getElementById('help-modal');
    const closeHelp = document.getElementById('close-help');
    const imageViewer = document.getElementById('image-viewer');
    const zoomIn = document.getElementById('zoom-in');
    const zoomOut = document.getElementById('zoom-out');
    const zoomReset = document.getElementById('zoom-reset');
    const viewOriginal = document.getElementById('view-original');
    const viewMask = document.getElementById('view-mask');
    const viewCombined = document.getElementById('view-combined');

    // 颜色阈值输入
    const greenLowInput = document.getElementById('green-low');
    const greenHighInput = document.getElementById('green-high');
    const yellowLowInput = document.getElementById('yellow-low');
    const yellowHighInput = document.getElementById('yellow-high');

    // 全局变量
    let uploadedImages = [];
    let activeImageIndex = -1;
    let chartInstance = null;
    let isDarkMode = false;
    let currentScale = 1;
    let colorMasks = {
        green: null,
        yellow: null,
        combined: null
    };

    // 初始化事件监听
    function initEventListeners() {
        // 主题切换
        themeToggle.addEventListener('click', toggleTheme);

        // 上传区域点击触发文件选择
        uploadArea.addEventListener('click', () => {
            fileUpload.click();
        });

        // 阻止拖拽默认行为
        ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
            uploadArea.addEventListener(eventName, preventDefaults, false);
        });

        function preventDefaults(e) {
            e.preventDefault();
            e.stopPropagation();
        }

        // 拖拽样式变化
        ['dragenter', 'dragover'].forEach(eventName => {
            uploadArea.addEventListener(eventName, highlight, false);
        });

        ['dragleave', 'drop'].forEach(eventName => {
            uploadArea.addEventListener(eventName, unhighlight, false);
        });

        function highlight() {
            uploadArea.classList.add('border-primary');
            uploadArea.classList.add('bg-green-50');
        }

        function unhighlight() {
            uploadArea.classList.remove('border-primary');
            uploadArea.classList.remove('bg-green-50');
        }

        // 处理文件拖放
        uploadArea.addEventListener('drop', handleDrop, false);

        function handleDrop(e) {
            const dt = e.dataTransfer;
            const files = dt.files;
            handleFiles(files);
        }

        // 处理文件选择
        fileUpload.addEventListener('change', function() {
            handleFiles(this.files);
        });

        // 开始检测按钮
        startDetection.addEventListener('click', startDetectionProcess);

        // 导出结果按钮
        exportResult.addEventListener('click', exportResults);

        // 清除按钮
        clearAll.addEventListener('click', clearAllData);

        // 帮助模态框
        helpBtn.addEventListener('click', () => {
            helpModal.classList.remove('hidden');
        });

        closeHelp.addEventListener('click', () => {
            helpModal.classList.add('hidden');
        });

        helpModal.addEventListener('click', (e) => {
            if (e.target === helpModal) {
                helpModal.classList.add('hidden');
            }
        });

        // 图片缩放控制
        zoomIn.addEventListener('click', () => {
            currentScale += 0.2;
            updateImageScale();
        });

        zoomOut.addEventListener('click', () => {
            currentScale = Math.max(0.4, currentScale - 0.2);
            updateImageScale();
        });

        zoomReset.addEventListener('click', () => {
            currentScale = 1;
            updateImageScale();
        });

        // 视图切换
        viewOriginal.addEventListener('click', () => {
            setActiveView('original');
        });

        viewMask.addEventListener('click', () => {
            setActiveView('mask');
        });

        viewCombined.addEventListener('click', () => {
            setActiveView('combined');
        });
    }

    // 更新图片缩放
    function updateImageScale() {
        previewImage.style.transform = `scale(${currentScale})`;
    }

    // 设置活动视图
    function setActiveView(viewType) {
        // 更新按钮状态
        [viewOriginal, viewMask, viewCombined].forEach(btn => {
            btn.classList.remove('active', 'bg-primary', 'text-white');
            btn.classList.add('text-gray-700');
        });

        // 根据视图类型设置
        switch(viewType) {
            case 'original':
                viewOriginal.classList.add('active', 'bg-primary', 'text-white');
                viewOriginal.classList.remove('text-gray-700');
                maskOverlay.style.opacity = '0';
                break;
            case 'mask':
                viewMask.classList.add('active', 'bg-primary', 'text-white');
                viewMask.classList.remove('text-gray-700');
                maskOverlay.style.opacity = '1';
                break;
            case 'combined':
                viewCombined.classList.add('active', 'bg-primary', 'text-white');
                viewCombined.classList.remove('text-gray-700');
                maskOverlay.style.opacity = '0.5';
                break;
        }
    }

    // 处理上传的文件
    function handleFiles(files) {
        if (!files.length) return;

        // 过滤非图片文件
        const imageFiles = Array.from(files).filter(file =>
            file.type.startsWith('image/')
        );

        if (imageFiles.length === 0) {
            alert('请选择图片文件（JPG、PNG格式）');
            return;
        }

        // 处理每个图片文件
        imageFiles.forEach(file => {
            const reader = new FileReader();

            reader.onload = function(e) {
                // 添加到上传图片列表
                const imageData = {
                    id: Date.now() + Math.floor(Math.random() * 1000),
                    src: e.target.result,
                    name: file.name,
                    detected: false,
                    results: null,
                    masks: null
                };

                uploadedImages.push(imageData);

                // 更新缩略图
                updateThumbnails();

                // 如果是第一张图片，自动显示
                if (uploadedImages.length === 1) {
                    showImage(0);
                }

                // 启用检测按钮
                startDetection.disabled = false;
            };

            reader.readAsDataURL(file);
        });
    }

    // 更新缩略图显示
    function updateThumbnails() {
        // 清空现有缩略图（保留最后一个加号）
        while (imageThumbs.firstChild) {
            imageThumbs.removeChild(imageThumbs.firstChild);
        }

        // 添加上传的图片缩略图
        uploadedImages.forEach((image, index) => {
            const thumbContainer = document.createElement('div');
            thumbContainer.className = `w-20 h-20 rounded-lg overflow-hidden border-2 cursor-pointer transition-all-300 ${
                index === activeImageIndex ? 'border-primary' : 'border-transparent hover:border-gray-300'
            }`;

            const thumbImg = document.createElement('img');
            thumbImg.src = image.src;
            thumbImg.alt = image.name;
            thumbImg.className = 'w-full h-full object-cover';

            // 如果已检测，添加标记
            if (image.detected) {
                const badge = document.createElement('div');
                badge.className = 'absolute bottom-1 right-1 bg-primary text-white text-xs px-1.5 py-0.5 rounded';
                badge.textContent = '已分析';
                thumbContainer.classList.add('relative');
                thumbContainer.appendChild(badge);
            }

            thumbContainer.appendChild(thumbImg);
            thumbContainer.addEventListener('click', () => showImage(index));

            imageThumbs.appendChild(thumbContainer);
        });

        // 添加"添加图片"按钮
        const addButton = document.createElement('div');
        addButton.className = 'text-gray-400 text-sm flex items-center justify-center w-20 h-20 border-2 border-dashed rounded-lg hover:border-primary hover:text-primary cursor-pointer transition-all-300';
        addButton.innerHTML = '<i class="fa fa-plus"></i>';
        addButton.addEventListener('click', () => fileUpload.click());
        imageThumbs.appendChild(addButton);
    }

    // 显示指定索引的图片
    function showImage(index) {
        if (index < 0 || index >= uploadedImages.length) return;

        activeImageIndex = index;
        const image = uploadedImages[index];

        // 重置缩放
        currentScale = 1;

        // 更新预览
        initialState.classList.add('hidden');
        previewContainer.classList.remove('hidden');
        previewImage.src = image.src;
        previewImage.alt = image.name;
        updateImageScale();

        // 清除之前的检测框和掩码
        detectionOverlays.innerHTML = '';
        maskOverlay.innerHTML = '';
        colorMasks = { green: null, yellow: null, combined: null };

        // 设置默认视图
        setActiveView('original');

        // 如果已有检测结果，显示
        if (image.detected && image.results) {
            showDetectionResults(image.results);

            // 如果有掩码数据，显示
            if (image.masks) {
                colorMasks = image.masks;
                maskOverlay.innerHTML = `<img src="${colorMasks.combined}" alt="颜色掩码" class="w-full h-auto">`;
            }
        } else {
            // 隐藏结果面板
            resultStats.classList.add('hidden');
            noDataState.classList.remove('hidden');
            growthState.classList.add('hidden');
            noGrowthData.classList.remove('hidden');
            careAdvice.classList.add('hidden');
            noAdvice.classList.remove('hidden');
            exportResult.disabled = true;
        }

        // 更新缩略图选中状态
        updateThumbnails();
    }

    // 解析颜色阈值
    function parseColorThresholds(input) {
        const values = input.split(',').map(v => parseInt(v.trim()));
        if (values.length !== 3 || values.some(isNaN)) {
            throw new Error('颜色阈值格式不正确，应为"h,s,v"格式');
        }
        return values;
    }

    // 开始检测过程
    function startDetectionProcess() {
        if (activeImageIndex < 0) return;

        const image = uploadedImages[activeImageIndex];

        // 获取选中的检测模式
        const detectionMode = document.querySelector('input[name="detection-mode"]:checked').value;

        // 验证颜色阈值
        try {
            parseColorThresholds(greenLowInput.value);
            parseColorThresholds(greenHighInput.value);
            parseColorThresholds(yellowLowInput.value);
            parseColorThresholds(yellowHighInput.value);
        } catch (e) {
            alert(e.message);
            return;
        }

        // 显示加载状态
        initialState.classList.add('hidden');
        previewContainer.classList.add('hidden');
        loadingState.classList.remove('hidden');

        // 重置进度条
        progressBar.style.width = '0%';
        progressText.textContent = '0% 完成';

        // 根据选择的模式进行检测
        if (detectionMode === 'color') {
            detectUsingColorAnalysis(image);
        } else {
            detectUsingYolo(image);
        }
    }

    // 基于颜色分析的检测（模拟OpenCV实现）
    function detectUsingColorAnalysis(image) {
        // 获取颜色阈值
        const greenLow = parseColorThresholds(greenLowInput.value);
        const greenHigh = parseColorThresholds(greenHighInput.value);
        const yellowLow = parseColorThresholds(yellowLowInput.value);
        const yellowHigh = parseColorThresholds(yellowHighInput.value);

        // 创建一个临时图像用于处理
        const tempImg = new Image();
        tempImg.src = image.src;

        tempImg.onload = function() {
            // 创建画布进行图像处理
            const canvas = document.createElement('canvas');
            const ctx = canvas.getContext('2d');
            canvas.width = tempImg.width;
            canvas.height = tempImg.height;
            ctx.drawImage(tempImg, 0, 0);

            // 获取图像数据
            const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
            const data = imageData.data;

            // 创建绿色和黄色掩码画布
            const greenCanvas = document.createElement('canvas');
            const yellowCanvas = document.createElement('canvas');
            const combinedCanvas = document.createElement('canvas');

            greenCanvas.width = canvas.width;
            greenCanvas.height = canvas.height;
            yellowCanvas.width = canvas.width;
            yellowCanvas.height = canvas.height;
            combinedCanvas.width = canvas.width;
            combinedCanvas.height = canvas.height;

            const greenCtx = greenCanvas.getContext('2d');
            const yellowCtx = yellowCanvas.getContext('2d');
            const combinedCtx = combinedCanvas.getContext('2d');

            greenCtx.drawImage(tempImg, 0, 0);
            yellowCtx.drawImage(tempImg, 0, 0);
            combinedCtx.drawImage(tempImg, 0, 0);

            // 获取掩码上下文数据
            const greenMaskData = greenCtx.getImageData(0, 0, canvas.width, canvas.height);
            const yellowMaskData = yellowCtx.getImageData(0, 0, canvas.width, canvas.height);
            const combinedMaskData = combinedCtx.getImageData(0, 0, canvas.width, canvas.height);

            let greenPixelCount = 0;
            let yellowPixelCount = 0;
            let totalPixelCount = 0;

            // 模拟HSV颜色空间转换和阈值过滤
            // 实际应用中，这里应该使用OpenCV.js或后端实现真正的HSV转换
            for (let i = 0; i < data.length; i += 4) {
                const r = data[i];
                const g = data[i + 1];
                const b = data[i + 2];

                // 简化的RGB到HSV转换（实际应用中应使用精确转换）
                const max = Math.max(r, g, b);
                const min = Math.min(r, g, b);
                const h = calculateHue(r, g, b, max, min);
                const s = max === 0 ? 0 : (max - min) / max * 100;
                const v = max / 255 * 100;

                // 归一化到0-255范围
                const hNorm = h / 360 * 255;
                const sNorm = s / 100 * 255;
                const vNorm = v / 100 * 255;

                // 检查是否在绿色范围内
                const isGreen = hNorm >= greenLow[0] && hNorm <= greenHigh[0] &&
                    sNorm >= greenLow[1] && sNorm <= greenHigh[1] &&
                    vNorm >= greenLow[2] && vNorm <= greenHigh[2];

                // 检查是否在黄色范围内
                const isYellow = hNorm >= yellowLow[0] && hNorm <= yellowHigh[0] &&
                    sNorm >= yellowLow[1] && sNorm <= yellowHigh[1] &&
                    vNorm >= yellowLow[2] && vNorm <= yellowHigh[2];

                // 只统计叶片像素
                if (isGreen || isYellow) {
                    totalPixelCount++;

                    if (isGreen) {
                        greenPixelCount++;
                        // 在绿色掩码上标记
                        greenMaskData.data[i] = 0;
                        greenMaskData.data[i + 1] = 255;
                        greenMaskData.data[i + 2] = 0;
                        greenMaskData.data[i + 3] = 100;

                        // 在组合掩码上标记绿色
                        combinedMaskData.data[i] = 0;
                        combinedMaskData.data[i + 1] = 255;
                        combinedMaskData.data[i + 2] = 0;
                        combinedMaskData.data[i + 3] = 100;
                    }

                    if (isYellow) {
                        yellowPixelCount++;
                        // 在黄色掩码上标记
                        yellowMaskData.data[i] = 255;
                        yellowMaskData.data[i + 1] = 255;
                        yellowMaskData.data[i + 2] = 0;
                        yellowMaskData.data[i + 3] = 100;

                        // 如果不是绿色，在组合掩码上标记黄色
                        if (!isGreen) {
                            combinedMaskData.data[i] = 255;
                            combinedMaskData.data[i + 1] = 255;
                            combinedMaskData.data[i + 2] = 0;
                            combinedMaskData.data[i + 3] = 100;
                        }
                    }
                } else {
                    // 非叶片区域设为透明
                    greenMaskData.data[i + 3] = 0;
                    yellowMaskData.data[i + 3] = 0;
                    combinedMaskData.data[i + 3] = 0;
                }
            }

            // 更新掩码数据
            greenCtx.putImageData(greenMaskData, 0, 0);
            yellowCtx.putImageData(yellowMaskData, 0, 0);
            combinedCtx.putImageData(combinedMaskData, 0, 0);

            // 转换为数据URL
            const greenMaskUrl = greenCanvas.toDataURL();
            const yellowMaskUrl = yellowCanvas.toDataURL();
            const combinedMaskUrl = combinedCanvas.toDataURL();

            // 计算黄叶率
            const totalLeaves = greenPixelCount + yellowPixelCount;
            const yellowPercentage = totalLeaves > 0 ? (yellowPixelCount / totalLeaves) * 100 : 0;

            // 计算健康评分（基于黄叶率）
            let healthScore = 100 - (yellowPercentage * 1.5);
            if (healthScore < 0) healthScore = 0;

            // 叶片颜色均匀度
            const uniformityScore = Math.floor(100 - (yellowPercentage * 0.8));

            // 确定生长状态
            let status, statusDesc, statusColor;
            if (yellowPercentage < 10) {
                status = '生长状态良好';
                statusDesc = '叶片健康，黄叶比例正常';
                statusColor = 'bg-primary';
            } else if (yellowPercentage < 30) {
                status = '轻微黄叶现象';
                statusDesc = '存在少量黄叶，需注意养护';
                statusColor = 'bg-yellow-500';
            } else {
                status = '黄叶问题明显';
                statusDesc = '黄叶比例较高，需要及时处理';
                statusColor = 'bg-danger';
            }

            // 生成养护建议
            let advice = [];
            if (yellowPercentage < 10) {
                advice = [
                    "继续保持当前养护方式，生长状态良好",
                    "定期浇水，保持土壤湿润但不过湿",
                    "放置在光线充足但避免阳光直射的位置"
                ];
            } else if (yellowPercentage < 30) {
                advice = [
                    "减少浇水频率，检查土壤排水情况",
                    "适当增加散射光照时间",
                    "可考虑施加少量有机肥改善土壤"
                ];
            } else {
                advice = [
                    "立即检查是否浇水过多导致根部问题",
                    "移除严重黄叶，避免养分消耗",
                    "调整至通风良好、光照适宜的环境",
                    "建议使用专用植物营养液补充养分"
                ];
            }

            // 构建结果对象
            const results = {
                totalPixels: totalLeaves,
                yellowPixels: yellowPixelCount,
                healthyPixels: greenPixelCount,
                yellowPercentage: yellowPercentage.toFixed(1),
                method: "颜色分析（OpenCV）",
                healthScore: Math.floor(healthScore),
                uniformityScore: Math.max(0, uniformityScore),
                status: status,
                statusDesc: statusDesc,
                statusColor: statusColor,
                advice: advice
            };

            // 保存掩码
            const masks = {
                green: greenMaskUrl,
                yellow: yellowMaskUrl,
                combined: combinedMaskUrl
            };

            // 模拟进度更新
            simulateProgress(() => {
                // 保存结果
                image.detected = true;
                image.results = results;
                image.masks = masks;

                // 隐藏加载状态，显示结果
                loadingState.classList.add('hidden');
                previewContainer.classList.remove('hidden');

                // 显示掩码
                maskOverlay.innerHTML = `<img src="${combinedMaskUrl}" alt="颜色掩码" class="w-full h-auto">`;

                // 显示检测结果
                showDetectionResults(results);

                // 更新缩略图
                updateThumbnails();

                // 启用导出按钮
                exportResult.disabled = false;
            });
        };
    }

    // 基于YOLO的检测（模拟）
    function detectUsingYolo(image) {
        // 模拟YOLO检测过程，实际应用中应调用真实的YOLO模型

        // 创建一个临时图像用于处理
        const tempImg = new Image();
        tempImg.src = image.src;

        tempImg.onload = function() {
            // 生成随机但合理的检测结果
            const totalLeaves = Math.floor(Math.random() * 30) + 10; // 10-40片叶子
            const yellowPercentage = Math.floor(Math.random() * 50); // 0-50%黄叶率
            const yellowCount = Math.floor(totalLeaves * yellowPercentage / 100);
            const healthyCount = totalLeaves - yellowCount;

            // 计算健康评分
            let healthScore = 100 - (yellowPercentage * 1.2);
            if (healthScore < 0) healthScore = 0;

            // 叶片颜色均匀度
            const uniformityScore = Math.floor(100 - (yellowPercentage * 0.6));

            // 确定生长状态
            let status, statusDesc, statusColor;
            if (yellowPercentage < 10) {
                status = '生长状态良好';
                statusDesc = '叶片健康，黄叶比例正常';
                statusColor = 'bg-primary';
            } else if (yellowPercentage < 30) {
                status = '轻微黄叶现象';
                statusDesc = '存在少量黄叶，需注意养护';
                statusColor = 'bg-yellow-500';
            } else {
                status = '黄叶问题明显';
                statusDesc = '黄叶比例较高，需要及时处理';
                statusColor = 'bg-danger';
            }

            // 生成养护建议
            let advice = [];
            if (yellowPercentage < 10) {
                advice = [
                    "继续保持当前养护方式，生长状态良好",
                    "定期浇水，保持土壤湿润但不过湿",
                    "放置在光线充足但避免阳光直射的位置"
                ];
            } else if (yellowPercentage < 30) {
                advice = [
                    "减少浇水频率，检查土壤排水情况",
                    "适当增加散射光照时间",
                    "可考虑施加少量有机肥改善土壤"
                ];
            } else {
                advice = [
                    "立即检查是否浇水过多导致根部问题",
                    "移除严重黄叶，避免养分消耗",
                    "调整至通风良好、光照适宜的环境",
                    "建议使用专用植物营养液补充养分"
                ];
            }

            // 构建结果对象
            const results = {
                totalPixels: totalLeaves,
                yellowPixels: yellowCount,
                healthyPixels: healthyCount,
                yellowPercentage: yellowPercentage.toFixed(1),
                method: "深度学习（YOLO）",
                healthScore: Math.floor(healthScore),
                uniformityScore: Math.max(0, uniformityScore),
                status: status,
                statusDesc: statusDesc,
                statusColor: statusColor,
                advice: advice,
                leaves: [] // 叶片检测框数据
            };

            // 生成随机叶片位置（模拟YOLO检测结果）
            for (let i = 0; i < totalLeaves; i++) {
                const isYellow = i < yellowCount;
                results.leaves.push({
                    id: i,
                    type: isYellow ? 'yellow' : 'healthy',
                    confidence: (85 + Math.random() * 15).toFixed(1), // 85-100%置信度
                    position: {
                        x: 5 + Math.random() * 90, // 5-95%
                        y: 5 + Math.random() * 90, // 5-95%
                        width: 4 + Math.random() * 12, // 4-16%
                        height: 4 + Math.random() * 12 // 4-16%
                    }
                });
            }

            // 模拟进度更新
            simulateProgress(() => {
                // 保存结果
                image.detected = true;
                image.results = results;

                // 隐藏加载状态，显示结果
                loadingState.classList.add('hidden');
                previewContainer.classList.remove('hidden');

                // 显示检测结果
                showDetectionResults(results);

                // 更新缩略图
                updateThumbnails();

                // 启用导出按钮
                exportResult.disabled = false;
            });
        };
    }

    // 模拟进度更新
    function simulateProgress(callback) {
        let progress = 0;
        const interval = setInterval(() => {
            progress += Math.random() * 10;
            if (progress > 100) progress = 100;

            progressBar.style.width = `${progress}%`;
            progressText.textContent = `${Math.round(progress)}% 完成`;

            if (progress === 100) {
                clearInterval(interval);
                setTimeout(callback, 500); // 延迟一点时间，让用户看到100%
            }
        }, 200);
    }

    // 计算色调（简化版）
    function calculateHue(r, g, b, max, min) {
        if (max === min) return 0;

        let h = 0;
        const d = max - min;

        switch (max) {
            case r:
                h = (g - b) / d + (g < b ? 6 : 0);
                break;
            case g:
                h = (b - r) / d + 2;
                break;
            case b:
                h = (r - g) / d + 4;
                break;
        }

        return h * 60;
    }

    // 显示检测结果
    function showDetectionResults(results) {
        // 显示统计数据
        noDataState.classList.add('hidden');
        resultStats.classList.remove('hidden');

        totalPixels.textContent = results.totalPixels;
        healthyPixels.textContent = results.healthyPixels;
        yellowPixels.textContent = results.yellowPixels;
        yellowRate.textContent = `${results.yellowPercentage}%`;
        detectionMethod.textContent = results.method;

        // 更新图表
        updateChart(parseFloat(results.yellowPercentage));

        // 绘制检测框（如果有）
        detectionOverlays.innerHTML = '';
        if (results.leaves && results.leaves.length > 0) {
            drawDetectionBoxes(results.leaves);
        }

        // 显示生长状态
        noGrowthData.classList.add('hidden');
        growthState.classList.remove('hidden');

        statusIndicator.className = `w-12 h-12 rounded-full flex items-center justify-center mr-3 ${results.statusColor}`;
        statusText.textContent = results.status;
        statusDesc.textContent = results.statusDesc;

        healthScore.textContent = results.healthScore;
        healthMeter.style.width = `${results.healthScore}%`;

        uniformityScore.textContent = results.uniformityScore;
        uniformityMeter.style.width = `${results.uniformityScore}%`;

        // 显示养护建议
        noAdvice.classList.add('hidden');
        careAdvice.classList.remove('hidden');

        adviceContent.innerHTML = '';
        results.advice.forEach(advice => {
            const p = document.createElement('p');
            p.className = 'flex items-start';
            p.innerHTML = `<i class="fa fa-check-circle text-primary mt-1 mr-2"></i>${advice}`;
            adviceContent.appendChild(p);
        });
    }

    // 更新饼图
    function updateChart(yellowPercentage) {
        const healthyPercentage = 100 - yellowPercentage;

        // 如果图表已存在，销毁它
        if (chartInstance) {
            chartInstance.destroy();
        }

        // 创建新图表
        const ctx = yellowLeafChart.getContext('2d');
        chartInstance = new Chart(ctx, {
            type: 'doughnut',
            data: {
                labels: ['健康叶片', '黄叶'],
                datasets: [{
                    data: [healthyPercentage, yellowPercentage],
                    backgroundColor: [
                        '#2E7D32', // 绿色 - 健康
                        '#FFA000'  // 黄色 - 黄叶
                    ],
                    borderWidth: 0,
                    cutout: '75%'
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: true,
                plugins: {
                    legend: {
                        position: 'bottom',
                        labels: {
                            padding: 20,
                            boxWidth: 12,
                            usePointStyle: true,
                            pointStyle: 'circle'
                        }
                    },
                    tooltip: {
                        callbacks: {
                            label: function(context) {
                                return `${context.label}: ${context.raw}%`;
                            }
                        }
                    }
                }
            }
        });
    }

    // 绘制检测框
    function drawDetectionBoxes(leaves) {
        // 为每个叶片创建检测框
        leaves.forEach(leaf => {
            const box = document.createElement('div');
            const pos = leaf.position;

            // 设置检测框样式和位置
            box.className = `absolute rounded-md border-2 ${
                leaf.type === 'healthy' ? 'border-primary bg-primary/10' : 'border-warning bg-warning/10'
            }`;

            box.style.left = `${pos.x}%`;
            box.style.top = `${pos.y}%`;
            box.style.width = `${pos.width}%`;
            box.style.height = `${pos.height}%`;

            // 添加标签
            const label = document.createElement('div');
            label.className = `absolute -top-6 left-0 px-2 py-0.5 text-xs font-medium rounded ${
                leaf.type === 'healthy' ? 'bg-primary text-white' : 'bg-warning text-white'
            }`;
            label.textContent = `${leaf.type === 'healthy' ? '健康叶' : '黄叶'} (${leaf.confidence}%)`;

            box.appendChild(label);
            detectionOverlays.appendChild(box);
        });
    }

    // 导出结果
    function exportResults() {
        if (activeImageIndex < 0) return;

        const image = uploadedImages[activeImageIndex];
        if (!image.detected || !image.results) return;

        // 创建结果对象
        const resultData = {
            图片名称: image.name,
            检测时间: new Date().toLocaleString(),
            检测方法: image.results.method,
            总叶片像素数: image.results.totalPixels,
            健康叶片像素数: image.results.healthyPixels,
            黄叶像素数: image.results.yellowPixels,
            黄叶率: `${image.results.yellowPercentage}%`,
            整体健康度: `${image.results.healthScore}/100`,
            叶片颜色均匀度: `${image.results.uniformityScore}/100`,
            生长状态评估: image.results.status,
            评估说明: image.results.statusDesc,
            养护建议: image.results.advice.join('; ')
        };

        // 转换为JSON字符串
        const jsonData = JSON.stringify(resultData, null, 2);
        const blob = new Blob([jsonData], { type: 'application/json' });
        const url = URL.createObjectURL(blob);

        // 创建下载链接
        const a = document.createElement('a');
        a.href = url;
        a.download = `植物黄叶检测结果_${image.name.replace(/\.\w+$/, '')}.json`;
        document.body.appendChild(a);
        a.click();

        // 清理
        setTimeout(() => {
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
        }, 0);
    }

    // 清除所有数据
    function clearAllData() {
        if (uploadedImages.length === 0) return;

        if (confirm('确定要清除所有上传的图片和检测结果吗？')) {
            uploadedImages = [];
            activeImageIndex = -1;

            // 重置界面
            initialState.classList.remove('hidden');
            previewContainer.classList.add('hidden');
            loadingState.classList.add('hidden');
            resultStats.classList.add('hidden');
            noDataState.classList.remove('hidden');
            growthState.classList.add('hidden');
            noGrowthData.classList.remove('hidden');
            careAdvice.classList.add('hidden');
            noAdvice.classList.remove('hidden');

            // 重置按钮状态
            startDetection.disabled = true;
            exportResult.disabled = true;

            // 更新缩略图
            updateThumbnails();

            // 销毁图表
            if (chartInstance) {
                chartInstance.destroy();
                chartInstance = null;
            }
        }
    }

    // 切换主题
    function toggleTheme() {
        isDarkMode = !isDarkMode;

        if (isDarkMode) {
            // 切换到深色模式
            appBody.classList.add('bg-neutral-dark');
            appBody.classList.add('text-gray-100');
            mainHeader.classList.add('bg-gray-800');
            mainHeader.classList.add('text-white');
            mainFooter.classList.add('bg-gray-800');
            mainFooter.classList.add('text-gray-400');
            themeToggle.innerHTML = '<i class="fa fa-sun-o mr-1"></i><span>浅色模式</span>';
        } else {
            // 切换到浅色模式
            appBody.classList.remove('bg-neutral-dark');
            appBody.classList.remove('text-gray-100');
            mainHeader.classList.remove('bg-gray-800');
            mainHeader.classList.remove('text-white');
            mainFooter.classList.remove('bg-gray-800');
            mainFooter.classList.remove('text-gray-400');
            themeToggle.innerHTML = '<i class="fa fa-moon-o mr-1"></i><span>深色模式</span>';
        }
    }

    // 初始化应用
    function initApp() {
        initEventListeners();
        updateThumbnails();
    }

    // 启动应用
    document.addEventListener('DOMContentLoaded', initApp);
</script>
</body>
</html>
